import logging
import logging.handlers
import os
from loki_logger import setup_loki_logger

# Loki配置
LOKI_URL = os.getenv('LOKI_URL', 'http://127.0.0.1:3100/loki/api/v1/push')
LOKI_USERNAME = os.getenv('LOKI_USERNAME')
LOKI_PASSWORD = os.getenv('LOKI_PASSWORD')

def setup_logger(name, log_dir='logs'):
    """设置日志记录器
    Args:
        name: 日志记录器名称
        log_dir: 日志文件目录
    Returns:
        logger: 配置好的日志记录器
    """
    # 创建日志目录
    if not os.path.exists(log_dir):
        os.makedirs(log_dir)
        
    # 创建日志记录器
    logger = logging.getLogger(name)
    logger.setLevel(logging.DEBUG)
    
    # 日志格式
    # formatter = logging.Formatter(
    #     '%(asctime)s - %(name)s - %(threadName)s - %(levelname)s - %(message)s'
    # )
    formatter = logging.Formatter(
        '%(asctime)s - %(name)s - %(threadName)s - %(levelname)s - %(filename)s:%(lineno)d - %(module)s - %(message)s'
    )
    
    # 控制台处理器
    console_handler = logging.StreamHandler()
    console_handler.setLevel(logging.INFO)
    console_handler.setFormatter(formatter)
    
    # 文件处理器 - 按天轮转
    file_handler = logging.handlers.TimedRotatingFileHandler(
        filename=os.path.join(log_dir, 'padbot.log'),
        when='midnight',
        interval=1,
        backupCount=30,  # 保留30天的日志
        encoding='utf-8'
    )
    file_handler.setLevel(logging.DEBUG)
    file_handler.setFormatter(formatter)
    
    # 错误日志处理器
    error_handler = logging.handlers.RotatingFileHandler(
        filename=os.path.join(log_dir, 'padbot_error.log'),
        maxBytes=10*1024*1024,  # 10MB
        backupCount=5,
        encoding='utf-8'
    )
    error_handler.setLevel(logging.ERROR)
    error_handler.setFormatter(formatter)
    
    # 添加所有处理器
    logger.addHandler(console_handler)
    logger.addHandler(file_handler)
    logger.addHandler(error_handler)
    
    # 设置Loki日志记录器
    if LOKI_URL:
        try:
            loki_logger = setup_loki_logger(
                name=name,
                loki_url=LOKI_URL,
                loki_username=LOKI_USERNAME,
                loki_password=LOKI_PASSWORD,
                tags={"service": name}
            )
            # 将Loki处理器添加到主日志记录器
            for handler in loki_logger.handlers:
                logger.addHandler(handler)
        except Exception as e:
            logger.error(f"Failed to setup Loki logging: {e}")
    
    return logger

# 创建主日志记录器
logger = setup_logger('padbot')
